/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.menuItem;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.MenuItem;
import com.blandware.atleap.service.core.MenuManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.MenuItemForm;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>Switches menu item visibility
 * </p>
 * <p><a href="SwitchMenuItemVisibilityAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.22 $ $Date: 2008/04/29 17:48:09 $
 * @struts.action path="/core/menuItem/switchVisibility"
 * name="menuItemForm"
 * validate="false"
 * roles="core-menuItem-switchVisibility"
 * @struts.action-forward name="listMenuItems"
 * path="/core/menuItem/list.do"
 * redirect="false"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/menuItem/list.do"
 */
public final class SwitchMenuItemVisibilityAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		MenuItemForm menuItemForm = (MenuItemForm) form;

        List selectedIds = (List) request.getAttribute(WebappConstants.MENU_ITEM_SELECTED_IDS_KEY);
        Map positions = (Map) request.getAttribute(WebappConstants.MENU_ITEM_POSITIONS_KEY);
        String ownerIdStr = (String) request.getAttribute(WebappConstants.MENU_ITEM_OWNER_ID_FOR_SELECTED_KEY);
        String modeStr = (String) request.getAttribute(WebappConstants.MENU_ITEM_VISIBILITY_MODE_FOR_SELECTED_KEY);
        request.removeAttribute(WebappConstants.MENU_ITEM_SELECTED_IDS_KEY);
        request.removeAttribute(WebappConstants.MENU_ITEM_POSITIONS_KEY);
        request.removeAttribute(WebappConstants.MENU_ITEM_OWNER_ID_FOR_SELECTED_KEY);
        request.removeAttribute(WebappConstants.MENU_ITEM_VISIBILITY_MODE_FOR_SELECTED_KEY);
        boolean multipleOperation = selectedIds != null;

		Long ownerId = null;
        if (multipleOperation) {
            if ( !GenericValidator.isBlankOrNull(ownerIdStr) ) {
                ownerId = Long.valueOf(ownerIdStr);
		    }
        } else {
            if ( !GenericValidator.isBlankOrNull(menuItemForm.getOwnerId()) ) {
			    ownerId = Long.valueOf(menuItemForm.getOwnerId());
		    }
        }
        if (ownerId == null) {
            if ( log.isWarnEnabled() ) {
                log.warn("Missing owner ID. Returning to index...");
            }
            return mapping.findForward("admin");
        }

		request.getSession().setAttribute(WebappConstants.OWNER_ID_KEY, ownerId);

        byte visibility = MenuItem.VISIBILITY_HERITABLE;
        String givenMode = null;
        if (multipleOperation) {
            givenMode = modeStr;
        } else {
            givenMode = request.getParameter("mode");
        }
        if ( givenMode != null ) {
            if ( "visible".equalsIgnoreCase(givenMode) ) {
                visibility = MenuItem.VISIBILITY_VISIBLE;
            } else if ( "invisible".equalsIgnoreCase(givenMode) ) {
                visibility = MenuItem.VISIBILITY_INVISIBLE;
            }
        }

        if (!multipleOperation) {
            if (GenericValidator.isBlankOrNull(menuItemForm.getId())) {
                if ( log.isWarnEnabled() ) {
                    log.warn("Missing menu item ID. Returning to list");
                }
                return mapping.findForward("listMenuItems");
            }
            selectedIds = new ArrayList();
            selectedIds.add(menuItemForm.getId());
            String alonePosition = null;
            if ( !GenericValidator.isBlankOrNull(request.getParameter("position")) ) {
                alonePosition = request.getParameter("position");
            }
            positions = new HashMap();
            positions.put(menuItemForm.getId(), alonePosition);
        }

        MenuManager menuManager = (MenuManager) getBean(Constants.MENU_MANAGER_BEAN);

        for (Iterator i = selectedIds.iterator(); i.hasNext(); ) {
            String menuItemIdStr = (String) i.next();
            if (GenericValidator.isBlankOrNull(menuItemIdStr)) {
                continue;
            }

            Long menuItemId = null;
            menuItemId = Long.valueOf(menuItemIdStr);

            Integer position = null;
            position = Integer.valueOf((String) positions.get(menuItemIdStr));

            // lookup for item with specified ID
            MenuItem menuItem = menuManager.retrieveMenuItem(menuItemId);

            if ( menuItem == null ) {
                // menuItem not found. it might be deleted by someone else
                ActionMessages errors = new ActionMessages();
                errors.add("menuItemNotFound", new ActionMessage("core.menuItem.errors.notFound"));
                saveErrors(request, errors);
                return mapping.findForward("listMenuItems");
            }

            Long parentItemId = null;
            if ( menuItem.getParentItem() != null ) {
                parentItemId = menuItem.getParentItem().getId();
            }

            // lookup for redefinition on current layer
            MenuItem redefinitionItem = null;
            if ( menuItem.getOwner() != null && menuItem.getOwner().getId().equals(ownerId) ) {
                // if this item was created on this layer, there is no need to create its redefinition
                redefinitionItem = menuItem;
            } else {
                redefinitionItem = menuManager.findRedefinitionItem(menuItem.getId(), ownerId);
            }

            if ( redefinitionItem == null ) {
                // redefinition does not exist, we must create it
                redefinitionItem = new MenuItem();
                redefinitionItem.setIdentifier(null);
                redefinitionItem.setPosition(position);
                redefinitionItem.setVisibility(new Byte(visibility));
                redefinitionItem.setOrigItem(menuItem);
                menuManager.createMenuItem(redefinitionItem, parentItemId, ownerId);
            } else {
                // redefinition already exists, change its visibility
                redefinitionItem.setVisibility(new Byte(visibility));
                try {
                    menuManager.updateMenuItem(redefinitionItem, parentItemId, ownerId);
                } catch ( ObjectOptimisticLockingFailureException e ) {
                    ActionMessages errors = new ActionMessages();
                    errors.add("updateFailed", new ActionMessage("core.menuItem.errors.updateFailed"));
                    saveErrors(request, errors);
                    return mapping.findForward("listMenuItems");
                }
            }

        }

		// flush cache
		CacheUtil cacheUtil = CacheUtil.getInstance(request);
		cacheUtil.flushMenuCache();
		cacheUtil.flushContentPageCache();

		return mapping.findForward("listMenuItems");
	}


}